package su.product.service.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import su.product.dao.ICateDAO;
import su.product.entity.Cate;
import su.product.service.CateService;

public class CateServiceImpl implements CateService {
	
	@Autowired
	private ICateDAO cateDAO;

	protected final Log log = LogFactory.getLog(getClass());
	//============================

	public List<Cate> getAllCates(int rootId) {
		List<Cate> list = null;
		try {
			 list = cateDAO.getByPid(rootId);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
	
	public Cate getById(int cateId){
		Cate cate = null;
		try {
			cate = cateDAO.getById(cateId);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return cate;
	}
	
	public String addCate(Cate o)throws Exception{
		//添加一个分类
		int id = cateDAO.insert(o);
		if(id==0)return "";
		//修改其父分类为非叶子
		cateDAO.updateCateLeaf(o.getPid(), 2);
		return String.valueOf(id);
	}
	
	public String remove(int id)throws Exception{
		Cate cate = cateDAO.getById(id);
		if(cate==null)return "数据库中没有数据，分类id="+id;
		if(cate.getProductnum()>0)return "该分类下还有产品信息，无法删除";
		//删除分类
		cateDAO.remove(id);
		//修改其父分类属性
		List<Cate> subCates = cateDAO.getByPid(cate.getPid());
		if(subCates==null || subCates.isEmpty()){
			cateDAO.updateCateLeaf(cate.getPid(), 1);
		}
		return "";
	}
	public void updateCateName(int id,String name)throws Exception{
		cateDAO.updateCateName(id, name);
	}
}
